/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.rational.sheet.table.adapter;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.KeyStroke;

/**
 *
 * @author Overmind
 */
public class RemoveTableAdapter
    implements ActionListener
{
    private static final KeyStroke delete;
    
    private JTable table = null;
    
    static
    {
	delete = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
    }
    
    public RemoveTableAdapter()
    {
        this(null);
    }
    
    public RemoveTableAdapter(JTable table)
    {
        setTable(table);
    }
    
    public JTable getTable()
    {
        return table;
    }
    
    public final void setTable(JTable newTable)
    {
        if(table != null)
        {
            table.unregisterKeyboardAction(delete);
        }
        
        table = newTable;
        
	if(table != null)
        {
            table.registerKeyboardAction(this, "Delete", delete, JComponent.WHEN_FOCUSED);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        if (e.getActionCommand().compareTo("Delete") == 0)
        {
            int numcols = table.getSelectedColumnCount();
            int numrows = table.getSelectedRowCount();
            int[] rowsselected = table.getSelectedRows();
            int[] colsselected = table.getSelectedColumns();
            
            for (int i = 0; i < numrows; i++)
            {
                for (int j = 0; j < numcols; j++)
                {
                    table.setValueAt("", rowsselected[i], colsselected[j]);
                }
            }
        }
    }
}
